package com.kcl.dfss;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.kcl.dfss.http.CameraConnection;
import com.kcl.dfss.http.ServerConnection;
import com.kcl.dfss.http.CameraConnection.ResponseHandler;
import com.kcl.dfss.utils.FTPUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class UpdateRomActivity extends Activity {

	protected static final String tag = "UpdateRomActivity";
	private LinearLayout updateRomback;
	private Button btn_upordown;
	private TextView tv_romno,tv_update;
	private ProgressDialog progressDialog = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_update_rom);
		
		updateRomback = (LinearLayout) findViewById(R.id.updateRomback);
		updateRomback.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btn_upordown = (Button) findViewById(R.id.btn_upordown);
		tv_romno = (TextView) findViewById(R.id.tv_romno);
		tv_update = (TextView) findViewById(R.id.tv_update);
		
		final SharedPreferences preferences = getSharedPreferences("shared_login", 0);
//		final String camera_romversion = preferences.getString("camera_romversion", "");
		final String app_romversion = preferences.getString("app_romversion", "1.0.0");
		
		Log.i(tag, "app_romversion:"+app_romversion);
		
		Intent intent = getIntent();
		boolean isconnect = intent.getBooleanExtra("isconnect", false); 
		Log.i(tag, "isconnect的值："+isconnect);
		if(isconnect){
			final Handler updateHandler = new Handler(){

				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					if(msg.what == 0){
						String response = (String)msg.obj;
						Log.i(tag, "上传ROM打印信息："+response);
						if(response.contains("fail")){
							progressDialog.dismiss();
							Toast.makeText(UpdateRomActivity.this, "ROM更新失败，请重试", Toast.LENGTH_SHORT).show();
						}else{
							progressDialog.dismiss();
							Toast.makeText(UpdateRomActivity.this, "ROM更新完成，重启设备后生效", Toast.LENGTH_SHORT).show();
							btn_upordown.setEnabled(false);
							btn_upordown.setBackgroundResource(R.drawable.changepwd_noclick);
						}
					}
				}
			};
			
			final Handler hanler = new Handler(){

				@Override
				public void handleMessage(Message msg) {
					final String camera_romversion = preferences.getString("camera_romversion", "");
					if(msg.what == 1){
						
						Log.i(tag, "app_romversion:"+app_romversion);
						Log.i(tag, "server_romversion:"+camera_romversion);
						
						if(camera_romversion.equals(app_romversion)){	//判断camera与app版本是否相同
							tv_romno.setText(app_romversion);
							tv_update.setText("当前ROM为最新版本，不需更新");
							btn_upordown.setEnabled(false);
							btn_upordown.setText("已是最新版本");
							btn_upordown.setBackgroundResource(R.drawable.changepwd_noclick);
						}else{
							if(fileExists(app_romversion)){	//判断ROM文件是否存在
								tv_romno.setText("当前版本号:"+camera_romversion);
								tv_update.setText("ROM已下载，可以更新");
								btn_upordown.setEnabled(true);
								btn_upordown.setText("开始更新");
								btn_upordown.setBackgroundResource(R.drawable.changepwd_selector);
								btn_upordown.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										progressDialog = android.app.ProgressDialog.show(UpdateRomActivity.this, "ROM更新", "ROM上传中，请勿退出...");
										new Thread(new Runnable() {
											@Override
											public void run() {
												FTPUtils.ftpUpload("192.168.1.1", "21", "root", "", 
														Environment.getExternalStorageDirectory().toString(),
														"/"+app_romversion);
												
												String md5 = FTPUtils.getFileMD5(new File(Environment.getExternalStorageDirectory().toString(),
														"/"+app_romversion));
												
												String result = CameraConnection.updateRom(app_romversion, "rootfs", app_romversion, md5);
												Log.i(tag, "update请求打印信息："+result);
												
												Message message = new Message();
												message.what = 0;
												message.obj = result;
												updateHandler.sendMessage(message);
											}
										}).start();
									}
								});
							}else{
								tv_romno.setText("当前版本号:"+camera_romversion);
								tv_update.setText("有新版本，建议在WiFi模式下载");
								btn_upordown.setEnabled(true);
								btn_upordown.setText("请断开设备后下载");
								btn_upordown.setEnabled(false);
								btn_upordown.setBackgroundResource(R.drawable.changepwd_noclick);
							}
						}
					}
				}
			};
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					String result = CameraConnection.getRomVersion();
					
					Log.i(tag, "result:"+result);
					
					preferences.edit().putString("camera_romversion", result).commit();
					Message messgae = new Message();
					messgae.what = 1;
					hanler.sendMessage(messgae);
				}
			}).start();
		}else{
			final Handler handler = new Handler(){

				@Override
				public void handleMessage(Message msg) {
					if(msg.what == 1){
						String server_romversion = preferences.getString("server_romversion", "");
						/*if(app_romversion.equals(server_romversion)){
							tv_romno.setText("当前版本:"+app_romversion);
							tv_update.setText("当前ROM为最新版本，不需更新");
							btn_upordown.setEnabled(false);
							btn_upordown.setBackgroundResource(R.drawable.changepwd_noclick);
						}else{
							if(fileExists(server_romversion)){
								tv_romno.setText("当前版本:"+app_romversion);
								tv_update.setText("ROM已下载，请连上设备后更新");
								btn_upordown.setText("开始更新");
								btn_upordown.setEnabled(false);
								btn_upordown.setBackgroundResource(R.drawable.changepwd_noclick);
							}else{
								tv_romno.setText("当前版本:"+app_romversion);
								tv_update.setText("有新版本，建议在WiFi模式下载");
								btn_upordown.setText("开始下载");
								btn_upordown.setEnabled(true);
								btn_upordown.setBackgroundResource(R.drawable.changepwd_selector);
								btn_upordown.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										Intent intent = new Intent();
										intent.putExtra("url", preferences.getString("romurl", ""));
										intent.putExtra("server_romversion", preferences.getString("server_romversion", ""));
										intent.setClass(UpdateRomActivity.this, DownLoadActivity.class);
										startActivity(intent);
									}
								});
							}
						}*/
						if(fileExists(app_romversion)){
							if(app_romversion.equals(server_romversion)){
								tv_romno.setText("当前版本:"+app_romversion);
								tv_update.setText("当前ROM为最新版本，不需更新");
								btn_upordown.setText("已是最新版本");
								btn_upordown.setEnabled(false);
								btn_upordown.setBackgroundResource(R.drawable.changepwd_noclick);
							}else{
								tv_romno.setText("当前版本:"+app_romversion);
								tv_update.setText("有新版本，建议在WiFi模式下载");
								btn_upordown.setText("开始下载");
								btn_upordown.setEnabled(true);
								btn_upordown.setBackgroundResource(R.drawable.changepwd_selector);
								btn_upordown.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										Intent intent = new Intent();
										intent.putExtra("url", preferences.getString("romurl", ""));
										intent.putExtra("server_romversion", preferences.getString("server_romversion", ""));
										intent.setClass(UpdateRomActivity.this, DownLoadActivity.class);
										startActivity(intent);
										finish();
									}
								});
							}
						}else{
							if(app_romversion.equals(server_romversion)){
								tv_romno.setText("当前版本:"+app_romversion);
								tv_update.setText("ROM包未下载，建议在WiFi模式下载");
								btn_upordown.setText("开始下载");
								btn_upordown.setEnabled(true);
								btn_upordown.setBackgroundResource(R.drawable.changepwd_selector);
								btn_upordown.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										Intent intent = new Intent();
										intent.putExtra("url", preferences.getString("romurl", ""));
										intent.putExtra("server_romversion", preferences.getString("server_romversion", ""));
										intent.setClass(UpdateRomActivity.this, DownLoadActivity.class);
										startActivity(intent);
										finish();
									}
								});
							}else{
								if(fileExists(server_romversion)){
									tv_romno.setText("当前版本:"+app_romversion);
									tv_update.setText("有新版本，建议在WiFi模式下载");
									btn_upordown.setText("新版本已下载");
									btn_upordown.setEnabled(false);
									btn_upordown.setBackgroundResource(R.drawable.changepwd_noclick);
								}else{
									tv_romno.setText("当前版本:"+app_romversion);
									tv_update.setText("有新版本，建议在WiFi模式下载");
									btn_upordown.setText("开始下载");
									btn_upordown.setEnabled(true);
									btn_upordown.setBackgroundResource(R.drawable.changepwd_selector);
									btn_upordown.setOnClickListener(new View.OnClickListener() {
										
										@Override
										public void onClick(View v) {
											Intent intent = new Intent();
											intent.putExtra("url", preferences.getString("romurl", ""));
											intent.putExtra("server_romversion", preferences.getString("server_romversion", ""));
											intent.setClass(UpdateRomActivity.this, DownLoadActivity.class);
											startActivity(intent);
											finish();
										}
									});
								}
							}
						}
					}
				}
			};
			
			new Thread(new Runnable() {

				@Override
				public void run() {
					String result = ServerConnection.GetRom("", "");
					try {
						
						Log.i(tag, "result:"+result);
						
						JSONObject jsonObject = new JSONObject(result);
						String data = jsonObject.getString("data");
						JSONObject object = new JSONObject(data);
						String server_romversion = object.getString("romversion");
						String romurl = object.getString("romurl");
						String md5 = object.getString("md5");
						
						Log.i(tag, "server_romversion:"+server_romversion);
						Log.i(tag, "romurl:"+romurl);
						Log.i(tag, "md5:"+md5);
						
						preferences.edit().putString("server_romversion", server_romversion).commit();
						preferences.edit().putString("romurl", romurl).commit();
						preferences.edit().putString("md5", md5).commit();
						Message messgae = new Message();
						messgae.what = 1;
						handler.sendMessage(messgae);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
		
	}
	
	/**
	 * 判断文件是否存在
	 */
	public boolean fileExists(String fileName){
		File file = new File(Environment.getExternalStorageDirectory()+"/"+fileName);
		if(file.exists()){
			return true;
		}else{
			return false;
		}
	}

	/*public void refresh(){
		finish();
		startActivity(new Intent(UpdateRomActivity.this, UpdateRomActivity.class));
	}*/
	
	@Override
	protected void onResume() {
		
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	

}
